package com.example.dbpage

import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.Toast
import com.example.dbpage.ListActivity.Companion.say
import com.example.dbpage.bean.Device
import com.example.dbpage.bean.Users
import com.example.dbpage.tool.DaoHelp
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking

class MainActivity : AppCompatActivity() {

    private var dao: DaoHelp? = null
    private var id: Long = -1

    //private val deviceDao: DeviceDao by lazy { DaoHelp.get(this).deviceDao() }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        dao = DaoHelp.get(this)


        btnInsert.setOnClickListener {
            insert()
        }


        btnQuery.setOnClickListener {
            query(id)
        }
    }


    fun insert() {

        if (age.text.isNullOrEmpty()) {
            Toast.makeText(this, "请输入年龄", Toast.LENGTH_SHORT).show()
            return
        }

        if (name.text.isNullOrEmpty()) {
            Toast.makeText(this, "请输入名字", Toast.LENGTH_SHORT).show()
            return
        }

        val mid = dao?.userDao()?.insert(Users(age.text.length, name.text.toString()))

        id = mid!!

        /*runBlocking {

            val mid = async { dao?.userDao()?.insert(Users(age.text.length, name.text.toString())) }.await()

            id = mid!!
        }*/
    }

    fun query(id: Long) {
        runBlocking {
            var users = async { dao?.userDao()?.getUserById(id) }.await()
            Log.i("tag", users.toString())
        }
    }


    fun insertdevice(view: View) {

        runBlocking {

            launch {
                var device = Device()
                device.carname = "小汽车"
                device.cartype = "车子"
                device.carbrand = "大众"
                val id: Long = dao?.deviceDao()?.insert(device)!!

                say(id.toString())
            }
        }
    }


    fun goto(view: View) {
        startActivity(Intent(this, ListActivity::class.java))
    }
}
